﻿using System;
using System.Collections.Generic;
using UnityEngine;

namespace MyGUI
{
    public class ListTabelTitle
    {
        List<TableTitle> titles = new List<TableTitle>();
        List<int> pos = new List<int>();
        public List<Action<Rect, TreeNode<ITableLine>>> rendererList = new List<Action<Rect, TreeNode<ITableLine>>>();
        public int Count
        {
            get { return titles.Count; }
        }

        public string this[int index]
        {
            get
            {
                return titles[index].title;
            }
        }

        public Rect GetRect(Rect rect, int index)
        {
            if (index >= pos.Count)
#if UNITY_5_3
                return new Rect(0, 0, 0, 0);
#else
                return Rect.zero;
#endif

            if (index != pos.Count - 1)
            {
                return new Rect(pos[index], rect.y, titles[index].width, rect.height);
            }
            else
            {
                return new Rect(pos[index], rect.y, rect.width - pos[index], rect.height);
            }
        }

        public void Renderer(int index,Rect rect, TreeNode<ITableLine> node)
        {
            if (index >= rendererList.Count)
                return;

            if (rendererList[index] == null)
                return;

            
            rendererList[index].Invoke(rect,node);
        }

        public void SetRenderer(int index, Action<Rect, TreeNode<ITableLine>> action)
        {
            if (index >= rendererList.Count)
                return;

            rendererList[index] = action;
        }

        public void Add(string title, int width)
        {
            titles.Add(new TableTitle(title, width));
            rendererList.Add(null);
            Update();
        }

        public void RemoveAt(int index)
        {
            titles.RemoveAt(index);
            rendererList.RemoveAt(index);
            Update();
        }

        void Update()
        {
            pos.Clear();

            int x = 0;
            for (int i = 0, count = titles.Count - 1; i < count; i++)
            {
                pos.Add(x);
                x += titles[i].width;
            }
            pos.Add(x);
        }

        struct TableTitle
        {
            public string title;
            public int width;
            public TableTitle(string title, int width)
            {
                this.title = title;
                this.width = width;
            }
        }
    }
}